package com.mall.user.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.JwtTokenUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * @ClassName: LoginServiceImpl
 * @Author: 南风
 * @Email: 1480207032@qq.com
 * @Description:
 * @Date: 2020/7/11 17:11
 */
@Service
public class LoginServiceImpl implements ILoginService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Override
    public UserLoginResponse login(UserLoginRequest userLoginRequest) {
        String username = userLoginRequest.getUserName();

        UserLoginResponse userLoginResponse = new UserLoginResponse();

        // 判空验证
        userLoginRequest.requestCheck();
        // 1、验证用户名是否存在
        //validUsernameExist(userLoginRequest.getUserName());
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userLoginRequest.getUserName());
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)){
            userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            return userLoginResponse;
        }


        Member member = members.get(0);

        // 2、验证密码是否正确
        //validUserpasswordCorrect(userLoginRequest);
        // password Md5 加密过
        String original = userLoginRequest.getPassword();
        String password = DigestUtils.md5DigestAsHex(original.getBytes());
        if (!password.equals(member.getPassword())){
            userLoginResponse.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
            userLoginResponse.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
            return userLoginResponse;
        }



        // 3、拿到数据返回
        userLoginResponse = getMemberInfoByUsername(userLoginResponse, username);

        userLoginResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        userLoginResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return userLoginResponse;
    }

    private UserLoginResponse getMemberInfoByUsername(UserLoginResponse userLoginResponse, String username) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", username);
        List<Member> members = memberMapper.selectByExample(example);
        Member member = members.size() >= 1 ? members.get(0):null;

        userLoginResponse.setId(member.getId());
        userLoginResponse.setUsername(member.getUsername());
        userLoginResponse.setPhone(member.getPhone());
        userLoginResponse.setEmail(member.getEmail());
        userLoginResponse.setSex(member.getSex());
        userLoginResponse.setAddress(member.getAddress());
        userLoginResponse.setFile(member.getFile());
        userLoginResponse.setDescription(member.getDescription());
        userLoginResponse.setPoints(member.getPoints());
        userLoginResponse.setBalance(member.getBalance());
        userLoginResponse.setState(member.getState());
        //token
        Long id = member.getId();
        String msg = id + "=" + username;
        String token = JwtTokenUtils.builder().msg(msg).build().creatJwtToken();
        userLoginResponse.setToken(token);

        return userLoginResponse;
    }

    @Override
    public CheckAuthResponse auth(CheckAuthRequest authRequest) {
        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();
        // 判空验证
        String token = authRequest.getToken();
        if (null == token){
            checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
            return checkAuthResponse;
        }
        // authRequest.requestCheck();
        // 1、分离参数，拿到token信息

        String msg = JwtTokenUtils.builder().token(token).build().freeJwt();
        String[] params = msg.split("=");
        // 2、根据token给的信息去验证权限
        Integer uid = Integer.parseInt(params[0]);
        // 用户激活验证
        Example memberExample = new Example(Member.class);
        memberExample.createCriteria().andEqualTo("id", uid);
        List<Member> members = memberMapper.selectByExample(memberExample);
        if (CollectionUtils.isEmpty(members)){
            // token信息错误
            checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
            return checkAuthResponse;
        }
        Member member = members.get(0);
        if (member.getIsVerified().equals("N")){
            // 用户未激活
            checkAuthResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            return checkAuthResponse;
        }
        // 用户权限验证
        String username = params[1];
        Example userVerifyExample = new Example(UserVerify.class);
        userVerifyExample.createCriteria().andEqualTo("username", username);
        List<UserVerify> userVerifies = userVerifyMapper.selectByExample(userVerifyExample);
        if (CollectionUtils.isEmpty(userVerifies)){
            checkAuthResponse.setCode(SysRetCodeConstants.TOKEN_VALID_FAILED.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.TOKEN_VALID_FAILED.getMessage());
            return checkAuthResponse;
        }
        UserVerify userVerify = userVerifies.get(0);
        if (userVerify.getIsVerify().equals("N")){
            // 没有权限
            checkAuthResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            return checkAuthResponse;
        }
        if (userVerify.getIsExpire().equals("Y")){
            // 权限过期
            checkAuthResponse.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
            return checkAuthResponse;
        }
        // 3、将结果返回

        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setUid(uid);
        userInfo.setUsername(username);

        checkAuthResponse.setUserinfo(userInfo);
        checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
        checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        return checkAuthResponse;
    }

    private void validUserpasswordCorrect(UserLoginRequest request) {
        // password Md5 加密过
        String original = request.getPassword();
        String password = DigestUtils.md5DigestAsHex(original.getBytes());
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", request.getUserName()).andEqualTo("password", password);
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)){
            throw new ValidateException(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode(),
                    SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
        }
    }

    private void validUsernameExist(String userName) {
        Example example = new Example(Member.class);
        example.createCriteria().andEqualTo("username", userName);
        List<Member> members = memberMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(members)){
            throw new ValidateException(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode(),
                    SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
        }
    }
}
